<template>
  <div>
    <div>
      <div class="bodyBox">
        <div class="messageRecording">
          <h2 style="">车列表 <a-icon @click="handleAddFriends" type="plus-circle"
              style="margin-left: 30px;cursor: pointer;" />
          </h2>
          <ul class="ul">
            <li v-for="(item, index) in vehicleList" :key="index" @click='clickVehicle(item.identificationCode, index)'
              :class="{ active_li: activeIndex === index }">
              <span>{{ item.identificationCode }}</span>
            </li>
          </ul>
        </div>
        <div class="chatting">
          <div class="messageBox" ref="QAContent">
            <ul class="content" id="gundong" @scroll="handleScroll">


              <li v-for="(item, index) in chatHistory" :key="item.id"
                :class='item.sender != activeIdentificationCode ? "flex-right" : "flex-left"'>
                <p class="message" v-if="item.type == 'text'">{{ item.message }}</p>
                <div class='audioBox' v-if="item.type == 'file'">
                  <div :class="'audioBox' + index" @click="handleAudio(index)" style='border-radius: 10px;
                        background: rgb(191, 236, 133);
                        width:100%;height:100%;
                        display:flex;
                        justify-content: space-between;
                        align-items: center;
                        padding: 1px 10px;
                        margin-bottom: 10px;'>
                    <span :id='"audioSec" + index'>{{ getDuration(index) }}</span>
                    <div class="box">
                      <div class="wifi-symbol">
                        <div class="wifi-circle first"></div>
                        <div class="wifi-circle second"></div>
                        <div class="wifi-circle third"></div>
                      </div>
                    </div>
                    <audio :id='"haorooms" + index' preload="auto" hidden="true">
                      <source :src="'/jeecg-boot/chat/nmcChatHistory/getOutputStreamById?id=' + item.id"
                        type="audio/mpeg">
                    </audio>
                  </div>
                </div>
              </li>
              <!-- <li>
                <p class="message">我通过你的好友请求，我们来聊天吧</p>
              </li>
              <li class="flex-right">
                <img src="" alt="" />
                <p class="message">你好，我是小艾</p>
              </li>
              <li>
                <p class="message">你好</p>
              </li>
              <li>
                <p class="message">你找我是有什么事吗？</p>
              </li> -->
            </ul>
          </div>
          <div class="operationArea">
            <a-tooltip placement="bottom">
              <template slot="title">
                <span>实时语音</span>
              </template>
              <a-icon type="phone" />
            </a-tooltip>

            <a-tooltip placement="bottom">
              <template slot="title">
                <span>聊天记录</span>
              </template>
              <a-icon type="clock-circle" />
            </a-tooltip>
            <a-tooltip placement="bottom">
              <template slot="title">
                <span>发送音频文件</span>
              </template>
              <a-upload :fileList="fileList" :show-upload-list="false" accept=".mp3" :action="uploadAction"
                :headers="headers"
                :data="{ identificationCode: activeIdentificationCode, fightDemandId: activeFightDemandId }"
                @change="handleChange">
                <a-icon type="folder" />
              </a-upload>
            </a-tooltip>
          </div>
          <div class="sendingArea">
            <a-textarea class="sendBox" v-model="sendValue"> </a-textarea>
            <div class="sendBtn">
              <a-button style="margin-right: 10px" type="primary" @click="resetSendValue">重置</a-button>
              <a-button style="margin-right: 10px" type="primary" @click="handleSend">发送</a-button>
            </div>
          </div>
        </div>
        <!--        <div class="protocolListDiv">-->
        <!--          <h2>协议表</h2>-->
        <!--          <ul class="ul">-->
        <!--            <li @click="selectProtocol(item)" v-for="item in protocolList" :key="item.id">-->
        <!--              <span style="cursor: pointer">{{ item.packageName }}</span>-->
        <!--            </li>-->
        <!--          </ul>-->
        <!--        </div>-->
      </div>
    </div>
    <a-modal :mask-closable="false" :mask="false" v-model="visible" title="发送音频列表" @ok="handleOk" cancel-text="取消"
      ok-text="发送" class="mp3ListModal">
      <ul class="ul">
        <li v-for="item in fileList" :key="item.uid"><img src="/music.png" alt="" /> {{ item.name }}</li>
      </ul>
    </a-modal>
    <handleAddFriends ref="handleAddFriends" @init="init" />
    <NmcPackageConfigForm ref="NmcPackageConfigForm" @ok="okEvent" />
  </div>
</template>
<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { httpAction, getAction } from '@/api/manage'
import NmcPackageConfigForm from './components/NmcPackageConfigForm.vue'
import handleAddFriends from './components/handleAddFriends'
import { mapGetters } from 'vuex'
export default {
  components: {
    NmcPackageConfigForm, handleAddFriends
  },
  computed: {
    ...mapGetters(['websocketMsg']),
    websocketMsg() {
      return this.$store.state.user.websocketMsg
    },
  },
  watch: {
    websocketMsg: {
      handler(val) {
        // 需要进行的操作
        let msg = JSON.parse(val)
        if (msg.cmd == 'CHAT') {
          this.loadChatHistory(1);
        }
      },
    },
    playAnimation: {
      handler(val) {
        //   let element=document.getElementsByClassName('audioBox2')[0]
        //   let audioDom=element.getElementsByClassName('audio')[0]
        //   console.log(element);
        //   let audio = document.getElementById('haorooms');
        // if(val){
        //     //播放动画
        //   element.getElementsByClassName('first')[0].style.webkitAnimationPlayState ='running'
        //   element.getElementsByClassName('second')[0].style.webkitAnimationPlayState ='running'
        //   element.getElementsByClassName('third')[0].style.webkitAnimationPlayState ='running'
        //   audio.play()

        // }else{
        //   //停止
        //   element.getElementsByClassName('first')[0].style.webkitAnimationPlayState ='paused'
        //   element.getElementsByClassName('second')[0].style.webkitAnimationPlayState ='paused'
        //   element.getElementsByClassName('third')[0].style.webkitAnimationPlayState ='paused'
        //   audio.pause()
        // }
      },
    }
  },
  data() {
    return {
      activeIndex: -1,
      activeIdentificationCode: null,
      activeVehicle: null,
      activeFightDemandId: null,
      chatHistory: [],
      messageList: [
        { id: 1, mes: '我通过你的好友请求，我们来聊天吧', status: 0 },
        { id: 2, mes: '你好', status: 0 },
        { id: 3, mes: '你好', status: 1 },
        { id: 4, mes: '找我啥事儿', status: 0 },
      ],
      visible: false,
      uploadAction: '/jeecg-boot/chat/nmcChatHistory/sendMp3',
      // uploadAction: window._CONFIG['domianURL'] + '/grid/nmcPackageGrid/list_sendmp3',
      fileList: [],
      headers: {},
      recordingList: [
        { id: 1, times: '2023/01/05 22:59:36', concent: '车入网申请' },
        { id: 2, times: '2024/01/05 21:19:31', concent: '车入网申请' },
      ],
      // 指挥车集合
      vehicleList: [],
      protocolList: [
        { id: 11, label: '车入网申请' },
        { id: 12, label: '车入网响应' },
        { id: 13, label: '车入网确认' },
        { id: 14, label: '车网络状态查询' },
        { id: 15, label: '车网络状态回复' },
      ],
      url: {
        sendMp3: '/grid/nmcPackageGrid/list_sendmp3',
        getProtocol: '/123url',
        getrRecordingList: '/recordingList', //消息记录列表
        getProtocolList: '/grid/nmcPackageInfo/list', //协议列表
        send: '/chat/nmcChatHistory/sendChat', //发送接口
        serializeDefaultValue2: '/grid/nmcPackageInfo/serializeDefaultValue2', //获取码流
        getCurrentRunningFightDemandFriends: "/chat/nmcChatFriends/getCurrentRunningFightDemandFriends", // 获取今日所有在网指挥车
        queryPageList: "/chat/nmcChatHistory/list",
      },
      searchValue: '',
      sendValue: '',
      packageCode: '',
      oldScrollTop: 0,
      scrollFlag: true,
      Intervall: null,
      playAnimation: false,
    }
  },
  created() {
    const token = this.$ls.get(ACCESS_TOKEN)
    this.headers = { 'X-Access-Token': token }
  },
  mounted() {
    this.init()
    this.scrollToBottom()
  },
  methods: {
    handleAddFriends() {
      this.$refs.handleAddFriends.showModal()
    },
    getDuration(val) {
      setTimeout(() => {
        let audio = document.getElementById(`haorooms${val}`);
        var duration = audio.duration;
        let dom = document.getElementById(`audioSec${val}`);
        let audioBox = document.getElementsByClassName(`audioBox${val}`)[0];
        dom.innerHTML = Math.round(duration)

        audioBox.style.background = '#bfec85'
        audioBox.style.borderRadius = '10px'
        if (duration < 10) {
          audioBox.style.width = '80px'
        } else if (duration < 20 && duration >= 10) {
          audioBox.style.width = '90px'
        } else if (duration < 30 && duration >= 20) {
          audioBox.style.width = '100px'
        } else if (duration < 40 && duration >= 50) {
          audioBox.style.width = '110px'
        } else if (duration < 50 && duration >= 60) {
          audioBox.style.width = '120px'
        } else {
          audioBox.style.width = '130px'
        }
        return Math.round(duration)
      }, 1500)



    },
    handleScroll(event) {
      const scrollTop = event.target.scrollTop;
      const isAtTop = scrollTop === 0;
      console.log(isAtTop ? '到达顶部' : '未到达顶部');
      // 根据isAtTop的值进行相应的操作
    },
    /**
     * 点击某个指挥车
     * @param identificationCode  点击的指挥车识别码
     * @param index  点击li的索引
     */
    clickVehicle(identificationCode, index) {
      this.activeIndex = index;
      this.activeIdentificationCode = identificationCode;
      for (let i = 0; i < this.vehicleList.length; i++) {
        if (this.vehicleList[i].identificationCode === identificationCode) {
          this.activeVehicle = this.vehicleList[i];
          this.activeFightDemandId = this.vehicleList[i].fightDemandId;
          break;
        }
      }
      this.loadChatHistory(1);
    },
    /**
     * 加载聊天记录
     * @param pageNo  页码
     */
    loadChatHistory(pageNo) {
      let param = {
        pageNo: pageNo,
        pageSize: 10,
        fightDemandId: this.activeVehicle.fightDemandId,
        receiver: this.activeIdentificationCode
      };
      let that = this;
      getAction(this.url.queryPageList, param).then(res => {
        if (res.success) {
          that.chatHistory = res.result.records.reverse();
        } else {
          that.$message.warning(res.message);
        }
      });
    },
    handleAudio(val) {
      this.playAnimation = !this.playAnimation

      let element = document.getElementsByClassName(`audioBox${val}`)[0]
      let audio = document.getElementById(`haorooms${val}`);
      let duration = audio.duration
      document.getElementById(`audioSec${val}`).innerHTML = Math.round(duration)
      audio.addEventListener('ended', function () {
        console.log('音频播放完毕');
        //停止
        element.getElementsByClassName('first')[0].style.webkitAnimationPlayState = 'paused'
        element.getElementsByClassName('second')[0].style.webkitAnimationPlayState = 'paused'
        element.getElementsByClassName('third')[0].style.webkitAnimationPlayState = 'paused'
        audio.pause()
      });
      if (this.playAnimation) {
        //播放动画
        element.getElementsByClassName('first')[0].style.webkitAnimationPlayState = 'running'
        element.getElementsByClassName('second')[0].style.webkitAnimationPlayState = 'running'
        element.getElementsByClassName('third')[0].style.webkitAnimationPlayState = 'running'
        audio.play()
      } else {
        //停止
        element.getElementsByClassName('first')[0].style.webkitAnimationPlayState = 'paused'
        element.getElementsByClassName('second')[0].style.webkitAnimationPlayState = 'paused'
        element.getElementsByClassName('third')[0].style.webkitAnimationPlayState = 'paused'
        audio.pause()

      }
    },
    showModal() {
      this.visible = true
    },
    handleOk(e) {
      console.log(e)
      this.visible = false
    },
    handleChange(info) {
      console.log(info, '--------')
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status == 'uploading') {
        console.log(info.file, info.fileList)
        //给个等待
      }
      // this.fileList = info.fileList
      // this.showModal()
      if (info.file.status === 'done') {
        //
        // console.log(info.fileList, 'fileListfileList')
        // this.fileList = info.fileList
        // this.showModal()
        this.$message.success(`${info.file.name} 发送成功`)
      } else if (info.file.status === 'error') {
        // console.log(info.fileList, 'fileListfileList')
        // this.fileList = info.fileList
        // this.showModal()
        this.$message.error(`${info.file.name}发送失败`)
      }
    },
    okEvent(data) {
      let params = { packageCode: this.packageCode, serializeItemDtoList: data }
      // console.log(data,'aaaaaaaaaa')
      httpAction(this.url.serializeDefaultValue2, params, 'post').then((res) => {
        this.sendValue = res.result
      })
    },
    resetSendValue() {
      this.sendValue = ''
      this.packageCode = ''
    },
    scrollToBottom() {
      // this.$nextTick 将回调延迟到下次DOM更新循环之后执行。在修改数据之后立即使用它，然后等待DOM更新
      this.$nextTick(() => {
        let msg = document.getElementById('gundong') // 获取对象
        console.log(msg.scrollHeight, '-----------')
        msg.scrollTop = msg.scrollHeight - msg.clientHeight // 滚动高度
      })
    },

    handleSend() {
      // this.$nextTick(() => {
      //   let msg = document.getElementById('gundong') // 获取对象
      //   console.log(msg.scrollHeight, '-----------')
      //   msg.scrollTop = msg.scrollHeight // 滚动高度
      // })
      // let flag = this.sendValue.length / 2 == 944
      // if (!flag) {
      //   this.$message.error('码流长度不够944字节！')
      //   return
      // }
      // let data = { packageCode: this.packageCode, hexString: this.sendValue }
      // httpAction(this.url.send, data, 'post').then((res) => {
      //   if (res.success) {
      //     this.$message.success(res.message)
      //     this.messageList.push({ id: this.messageList.length + 1, mes: this.sendValue, status: 1 })
      //     this.sendValue = ''
      //   } else {
      //     this.$message.error(res.message)
      //   }
      //
      //   //发送操作
      // })
      if (!this.activeIdentificationCode) {
        this.$message.warning("清先选择指挥车！")
        return;
      }
      if (!this.sendValue) {
        this.$message.warning("发送内容不能为空！")
        return;
      }

      let data = {
        receiver: this.activeVehicle.identificationCode,
        message: this.sendValue,
        fightDemandId: this.activeVehicle.fightDemandId
      };
      httpAction(this.url.send, data, 'post').then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.sendValue = '';
          //TODO 触发查询聊天记录
        } else {
          this.$message.error(res.message)
        }
      })

    },
    init() {
      let that = this;
      getAction(this.url.getCurrentRunningFightDemandFriends, { pageSize: -1 }).then((res) => {
        if (res.success) {
          that.vehicleList = res.result;
        } else {
          that.$message.warning(res.message);
        }
      })
    },
    selectProtocol(record) {
      this.packageCode = record.packageCode
      // 打开配置框
      this.$refs.NmcPackageConfigForm.edit(record)
      // httpAction(this.url.serializeDefaultValue2,{packageCode:id},'post').then(res => {

      //   this.sendValue=res.result
      // })
    },
    onSearch() {
      //查询操作
      console.log(this.searchValue)
    },
  },
}
</script>
<style lang="less" scoped>
.bodyBox {
  color: #fff;

  display: flex;
  width: 100%;
  height: calc(100vh - 170px);

  h2 {
    background-color: #0c345b;
    text-align: center;
    line-height: 50px;
  }

  .ul {
    padding: 0;
    color: #fff;

    li {
      list-style: none;
      font-size: 18px;
      text-align: center;
    }
  }

  .messageRecording {
    width: 300px;
    // background-color: pink;
    border: 1px solid #26fbf3;
  }

  .protocolListDiv {
    width: 300px;
    // background-color: aquamarine;
    border: 1px solid #26fbf3;
    overflow-y: scroll;

    li {
      text-align: left;
      padding-left: 20px;
    }
  }

  .chatting {
    flex-grow: 1;
    text-align: left;
    margin: 0 10px;
    padding: 3px;
    border: 1px solid #26fbf3;
    position: relative;
    height: 100%;
    // background-color: bisque;

    .searchBox {
      display: flex;
      width: 99%;
      position: absolute;
      top: 3;
      z-index: 2;
    }

    .operationArea {
      display: flex;
      height: 50px;

      .anticon {
        font-size: 30px;
        margin: 10px;
      }
    }

    .messageBox {
      height: 60%;

      .content {
        color: #726f6f;
        padding-top: 35px;
        width: 100%;
        // height: 300px;

        height: 100%;
        overflow-y: scroll;
        margin: 0 auto;
        // background-color: skyblue;
        border: 1px solid;
      }

      .flex-left {
        .audioBox {
          // border: 1px solid ;
          // border-radius: 10px;
          // background: rgb(191, 236, 133);
          // width:80px; 
          // display: flex;
          // flex-direction: row-reverse;
          min-width: 80px;
          height: 50px;

          span {
            font-size: 18px;
          }

          .box {
            width: 50px;
            height: 50px;
            box-sizing: border-box;
            position: relative;
            margin-right: -35px;
          }

          .wifi-symbol {
            width: 50px;
            height: 50px;
            box-sizing: border-box;
            overflow: hidden;
            transform: rotate(135deg);

          }

          .wifi-circle {
            border: 5px solid #999999;
            border-radius: 50%;
            position: absolute;
          }

          .first {
            width: 5px;
            height: 5px;
            background: #cccccc;
            top: 45px;
            left: 45px;
          }

          .second {
            width: 25px;
            height: 25px;
            top: 35px;
            left: 35px;
            animation: fadeInOut 1s infinite 0.2s;
            animation-play-state: paused;
          }

          .third {
            width: 40px;
            height: 40px;
            top: 25px;
            left: 25px;
            animation: fadeInOut 1s infinite 0.4s;
            animation-play-state: paused;
          }

          @keyframes fadeInOut {
            0% {
              opacity: 0;
              /*初始状态 透明度为0*/
            }

            100% {
              opacity: 1;
              /*结尾状态 透明度为1*/
            }
          }
        }
      }

      .content>li {
        display: flex;
        padding: 0 20px;
        overflow: hidden;
      }

      .message {
        position: relative;
        max-width: 400px;
        margin: 10px;
        padding: 10px 20PX 10PX 10PX;
        background-color: rgb(189, 238, 248);
        // border: 1px solid;
        border-radius: 5px;
        white-space: break-word !important;
        word-break: break-all;
      }

      .message::after {
        content: '';
        position: absolute;
        left: -5px;
        width: 15px;
        height: 15px;
        transform: rotate(45deg);
        background-color: rgb(189, 238, 248);
      }

      .flex-right {
        flex-direction: row-reverse;
        padding-right: 10px;

        .audioBox {
          display: flex;
          flex-direction: row-reverse;
          min-width: 80px;
          height: 50px;

          span {
            font-size: 18px;
          }

          .box {
            width: 50px;
            height: 50px;
            box-sizing: border-box;
            position: relative;
            margin-right: -35px;
          }

          .wifi-symbol {
            width: 50px;
            height: 50px;
            box-sizing: border-box;
            overflow: hidden;
            transform: rotate(135deg);

          }

          .wifi-circle {
            border: 5px solid #999999;
            border-radius: 50%;
            position: absolute;
          }

          .first {
            width: 5px;
            height: 5px;
            background: #cccccc;
            top: 45px;
            left: 45px;
          }

          .second {
            width: 25px;
            height: 25px;
            top: 35px;
            left: 35px;
            animation: fadeInOut 1s infinite 0.2s;
            animation-play-state: paused;
          }

          .third {
            width: 40px;
            height: 40px;
            top: 25px;
            left: 25px;
            animation: fadeInOut 1s infinite 0.4s;
            animation-play-state: paused;
          }

          @keyframes fadeInOut {
            0% {
              opacity: 0;
              /*初始状态 透明度为0*/
            }

            100% {
              opacity: 1;
              /*结尾状态 透明度为1*/
            }
          }
        }
      }

      .flex-right>.message::after {
        left: unset;
        right: -5px;
      }
    }

    .sendingArea {
      height: calc(40% - 50px);
      position: relative;

      // background-color: #26fbf3;
      .sendBox {
        border: 1px solid;
        height: calc(100% - 50px);
        padding-bottom: 30px;
      }

      .sendBtn {
        position: absolute;
        bottom: 5px;
        width: 100%;
        display: flex;
        justify-content: flex-end;
        padding: 5px;
      }
    }
  }
}
</style>
<style>
.active_li {
  border: 2px solid #ff6c00;
  color: #ff6c00;
  background: #fff7e9;
}

.messageBox .message {
  white-space: break-word !important;
}

.bodyBox .ant-upload {
  color: #fff !important;
  cursor: pointer;
}

.mp3ListModal .ant-modal-body img {
  width: 30px !important;
}

.mp3ListModal .ant-modal-body li {
  color: #fff !important;
  list-style: none !important;
}
</style>
<style scoped>
.consoleBox {
  width: 100%;
  min-height: 500px;
  max-height: 1780px;
  overflow-x: hidden;
  overflow-y: auto;
}

.consoleBox::-webkit-scrollbar {
  width: 10px !important;
  /*高宽分别对应横竖滚动条的尺寸*/
  height: 1px !important;
}

.consoleBox::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 10px !important;
  background-color: skyblue !important;
  /*background-color: 0096c7 !important;*/
  background-image: -webkit-linear-gradient(45deg,
      rgba(255, 255, 255, 0.2) 25%,
      transparent 25%,
      transparent 50%,
      rgba(255, 255, 255, 0.2) 50%,
      rgba(255, 255, 255, 0.2) 75%,
      transparent 75%,
      transparent);
}

.consoleBox::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #ededed;
  border-radius: 10px;
}
</style>
